// ==================== src/stores/attraction.js ====================
import { defineStore } from 'pinia'
import { ref } from 'vue'
import attractionApi  from '@/api/attraction.js'

export const useAttractionStore = defineStore('attraction', () => {
    const attractions = ref([])
    const districts = ref([])
    const loading = ref(false)
    const totalCount = ref(0)
    const pagination = ref({
        current: 1,
        size: 12,
        total: 0
    })

    // 查询参数
    const queryParams = ref({
        cityName: '',
        name: '',
        index: 1,
        sortType: 1,
        count: 12,
    })

    // 获取景点列表
    const fetchAttractions = async () => {
        try {
            loading.value = true
            const data = await attractionApi.getAttractions(queryParams.value)
            attractions.value = data.data.attractions || []
            totalCount.value = data.data.totalCount || 0
        } catch (error) {
            console.error('获取景点列表失败:', error)
            attractions.value = []
        } finally {
            loading.value = false
        }
    }

    // 获取景点列表
    const fetchCtripAttractions = async () => {
        try {
            loading.value = true
            const data = await attractionApi.getCtripAttractions(queryParams.value)
            attractions.value = data.data.attractions || []
            totalCount.value = data.data.totalCount || 0
        } catch (error) {
            console.error('获取携程景点列表失败:', error)
            attractions.value = []
        } finally {
            loading.value = false
        }
    }

    // 获取区域列表
    const fetchDistricts = async () => {
        try {
            const data = await attractionApi.getDistricts()
            districts.value = data.data || []
        } catch (error) {
            console.error('获取区域列表失败:', error)
            districts.value = []
        }
    }

    const deleteAttraction = async (poId) => {
        try {
            loading.value = true
            await attractionApi.deleteAttraction(poId)
            // 删除成功后，重新获取景点列表
            await fetchAttractions()
        } catch (error) {
            console.error('删除景点失败:', error)
        } finally {
            loading.value = false
        }
    }

    // 更新查询参数
    const updateQueryParams = (params) => {
        queryParams.value = { ...queryParams.value, ...params }
    }

    // 重置查询参数
    const resetQueryParams = () => {
        queryParams.value = {
            cityName: '',
            name: '',
            index: 1,
            sortType: 1,
            count: 12,
        }
    }

    return {
        attractions,
        districts,
        loading,
        pagination,
        queryParams,
        totalCount,
        fetchAttractions,
        deleteAttraction,
        fetchCtripAttractions,
        fetchDistricts,
        updateQueryParams,
        resetQueryParams
    }
})